package com.konne.nightmare.FastPublicOpinion.ui.information.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.location.AMapLocation;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.gyf.immersionbar.ImmersionBar;
import com.konne.nightmare.FastPublicOpinion.base.BaseMvpActivity;
import com.konne.nightmare.FastPublicOpinion.mvp.presenter.MainPresenter;
import com.konne.nightmare.FastPublicOpinion.mvp.view.IMainView;
import com.konne.nightmare.FastPublicOpinion.ui.information.fragment.EventFragment;
import com.konne.nightmare.FastPublicOpinion.ui.information.fragment.HomeFragment;
import com.konne.nightmare.FastPublicOpinion.ui.information.fragment.OpinionFragment;
import com.konne.nightmare.FastPublicOpinion.ui.information.fragment.UserFragment;
import com.konne.nightmare.FastPublicOpinion.ui.personal.activity.AccountSafeActivity;
import com.konne.nightmare.FastPublicOpinion.ui.personal.activity.DeviceManageActivity;
import com.konne.nightmare.FastPublicOpinion.ui.personal.activity.EditPersonalActivity;
import com.konne.nightmare.FastPublicOpinion.ui.personal.activity.HelpCenterActivity;
import com.konne.nightmare.FastPublicOpinion.ui.personal.activity.MyPassphraseActivity;
import com.konne.nightmare.FastPublicOpinion.ui.personal.activity.NoticeSetActivity;
import com.konne.nightmare.FastPublicOpinion.ui.personal.activity.PrivacySetActivity;
import com.konne.nightmare.FastPublicOpinion.utils.GaoDeMapUtils;
import com.konne.nightmare.FastPublicOpinion.utils.LoadProgressDialog;
import com.konne.nightmare.FastPublicOpinion.utils.PermissionUtils;
import com.konne.nightmare.FastPublicOpinion.R;
import com.konne.nightmare.FastPublicOpinion.utils.ToastUtil;
import com.konne.nightmare.FastPublicOpinion.ui.dialog.ConfirmDialog;

import java.util.List;

import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;


public class MainActivity extends BaseMvpActivity<IMainView, MainPresenter> implements BottomNavigationBar.OnTabSelectedListener, IMainView, EasyPermissions.PermissionCallbacks, View.OnClickListener {
    private BottomNavigationBar bottomNavigationBar;
    // Fragment管理器，和执行器
    private FragmentManager mManager;
    private FragmentTransaction mTransaction;
    private HomeFragment homeFragment;
    private OpinionFragment opinionFragment;
    private UserFragment userFragment;
    private EventFragment eventFragment;
    private long mExitTime;
    private DrawerLayout drawerLayout;
    private ImageView imgAvatar;
    private ImageView imgQRCode;
    private TextView tvCode;

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter();
    }


    @Override
    public int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {

        ImmersionBar.with(this)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
                .statusBarColor(R.color.transparent).fullScreen(true)
                .statusBarDarkFont(true)
                .init();

        PermissionUtils.allPermissionTask(this);
        bottomNavigationBar = findViewById(R.id.bottom_navigation_bar);
        bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        imgAvatar = (ImageView) findViewById(R.id.img_avatar);
        imgQRCode = (ImageView) findViewById(R.id.img_QR_code);
        tvCode = (TextView) findViewById(R.id.tv_code);

    }

    @OnClick({R.id.img_avatar, R.id.tv_exit_login, R.id.rl_device,
            R.id.rl_account_safe, R.id.rl_help_center, R.id.rl_notice_set, R.id.rl_privacy_set,
            R.id.ll_my_code})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_avatar:
                Intent intent = new Intent();
                intent.setClass(this, EditPersonalActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_exit_login:
                drawerLayout.closeDrawer(GravityCompat.START);
                showExitDialog();
                break;
            case R.id.rl_device:
                startActivity(new Intent(this, DeviceManageActivity.class));
                break;
            case R.id.rl_account_safe:
                startActivity(new Intent(this, AccountSafeActivity.class));
                break;
            case R.id.rl_help_center:
                startActivity(new Intent(this, HelpCenterActivity.class));
                break;
            case R.id.rl_notice_set:
                startActivity(new Intent(this, NoticeSetActivity.class));
                break;
            case R.id.rl_privacy_set:
                startActivity(new Intent(this, PrivacySetActivity.class));
                break;
            case R.id.ll_my_code:
                startActivity(new Intent(this, MyPassphraseActivity.class));
                break;
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mManager = getSupportFragmentManager();
        initBottomNavigationBar();

    }

    /**
     * 退出登录弹窗
     */
    private void showExitDialog() {

        final ConfirmDialog dialog = new ConfirmDialog(this);
        dialog.setMessageImage(R.mipmap.icon_exit_login);
        dialog.setMessage("确认要退出登录？");
        dialog.setOkButton("退出登录", v -> {
            Intent intent = new Intent();
            intent.setClass(this, LoginActivity.class);
            startActivity(intent);
            dialog.dismiss();
            finish();
        });
        dialog.setCancelButton("取消", v -> dialog.dismiss());
        dialog.show();
    }

    private void initBottomNavigationBar() {
        /**
         *  new BottomNavigationItem(R.mipmap.tab_home_pressed,"首页") ,选中的图标，文字
         *  setActiveColorResource：选中的颜色
         *  setInactiveIconResource：未选中的图标
         *  setInActiveColorResource：未选中的颜色
         */
        bottomNavigationBar
                .addItem(new BottomNavigationItem(R.drawable.home1, getString(R.string.home_field))
                        .setActiveColorResource(R.color.color_0E1216)
                        .setInactiveIconResource(R.drawable.home)
                        .setInActiveColorResource(R.color.color_999999))
                .addItem(new BottomNavigationItem(R.drawable.haiyou1, getString(R.string.opinion_field))
                        .setActiveColorResource(R.color.color_0E1216)
                        .setInactiveIconResource(R.drawable.haiyou)
                        .setInActiveColorResource(R.color.color_999999))
                .addItem(new BottomNavigationItem(R.drawable.xiaoxi2, getString(R.string.event_field))
                        .setActiveColorResource(R.color.color_0E1216)
                        .setInactiveIconResource(R.drawable.xiaoxi)
                        .setInActiveColorResource(R.color.color_999999))
                .addItem(new BottomNavigationItem(R.drawable.home1, getString(R.string.user_field))
                        .setActiveColorResource(R.color.color_0E1216)
                        .setInactiveIconResource(R.drawable.faxian)
                        .setInActiveColorResource(R.color.color_999999))
                .initialise();
        bottomNavigationBar.setTabSelectedListener(this);
        bottomNavigationBar.selectTab(0);
    }

    @Override
    public void onTabSelected(int position) {
        //开启事务
        mTransaction = mManager.beginTransaction();

        hideFragment(mTransaction);

        /**
         * fragment 用 add + show + hide 方式
         * 只有第一次切换会创建fragment，再次切换不创建
         *
         * fragment 用 replace 方式
         * 每次切换都会重新创建
         *
         */
        switch (position) {
            case 0:
                if (homeFragment == null) {
                    homeFragment = HomeFragment.newInstance();
                    mTransaction.add(R.id.ll_content,
                            homeFragment);
                    homeFragment.setOnPersonalClickListener(new HomeFragment.OnPersonalClickListener() {
                        @Override
                        public void click() {
                            drawerLayout.openDrawer(GravityCompat.START);
                        }
                    });
                } else {
                    mTransaction.show(homeFragment);
                }
                break;
            case 1:

                if (opinionFragment == null) {
                    opinionFragment = OpinionFragment.newInstance();
                    mTransaction.add(R.id.ll_content,
                            opinionFragment);
                } else {
                    mTransaction.show(opinionFragment);
                }
                break;
            case 2:

                if (eventFragment == null) {
                    eventFragment = EventFragment.newInstance();
                    mTransaction.add(R.id.ll_content,
                            eventFragment);
                } else {
                    mTransaction.show(eventFragment);
                }
                break;

            case 3:

                if (userFragment == null) {
                    userFragment = UserFragment.newInstance();
                    mTransaction.add(R.id.ll_content,
                            userFragment);
                } else {
                    mTransaction.show(userFragment);
                }
                break;
        }
        // 事务提交
        mTransaction.commit();
    }


    @Override
    public void onTabUnselected(int position) {

    }

    @Override
    public void onTabReselected(int position) {

    }

    @Override
    public LoadProgressDialog getLoadDialog() {
        return dialog;
    }

    @Override
    public void cancelLoadDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.cancel();
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (requestCode == PermissionUtils.RC_LOCATION_PERM) {
            GaoDeMapUtils gaoDeMapUtils = new GaoDeMapUtils(this);
            gaoDeMapUtils.setOnLocationPass(new GaoDeMapUtils.OnLocationPass() {
                @Override
                public void onLocation(AMapLocation aMapLocation) {

                }
            });
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    /**
     * 隐藏当前fragment
     *
     * @param transaction
     */
    private void hideFragment(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }

        if (opinionFragment != null) {
            transaction.hide(opinionFragment);
        }

        if (eventFragment != null) {
            transaction.hide(eventFragment);
        }
        if (userFragment != null) {
            transaction.hide(userFragment);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis()) < 2000 + mExitTime) {// System.currentTimeMillis()无论何时调用，肯定大于2000
                return super.onKeyDown(keyCode, event);
            } else {
                ToastUtil.showToast(getString(R.string.again_press_exit_app));
                mExitTime = System.currentTimeMillis();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}